package com.infinova.datax.apiwriter;

import com.alibaba.datax.common.element.Record;
import com.alibaba.datax.common.plugin.RecordReceiver;
import com.alibaba.datax.common.spi.Writer;
import com.alibaba.datax.common.util.Configuration;
import com.alibaba.fastjson2.JSONObject;
import com.infinova.datax.common.http.HttpClient;
import com.infinova.datax.common.http.HttpRequest;
import com.infinova.datax.common.http.OkHttp3Client;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

import static com.alibaba.fastjson2.JSONWriter.Feature.PrettyFormat;

/**
 * @author bigbird-0101
 * @date 2023-07-28 10:26
 */
public class ApiWriter extends Writer {
    public static class Job extends Writer.Job{
        private Configuration pluginJobConf;

        @Override
        public List<Configuration> split(int i) {
            List<Configuration> array=new ArrayList<>();
            for(int a=0;a<i;a++) {
                array.add(pluginJobConf.clone());
            }
            return array;
        }

        @Override
        public void init() {
            pluginJobConf = super.getPluginJobConf();
        }

        @Override
        public void destroy() {

        }
    }

    public static class Task extends Writer.Task{
        private final static Logger LOGGER = LoggerFactory.getLogger("com.infinova.datax.apiwriter.ApiWriter.ApiWriterTask");
        private HttpClient httpClient;
        private Config config;
        @Override
        public void startWrite(RecordReceiver recordReceiver) {
            Record record;
            while ((record = recordReceiver.getFromReader()) != null) {
                HttpRequest request = config.convert(record);
                JSONObject result = httpClient.handle(request, JSONObject.class);
                LOGGER.info("class result {}",JSONObject.toJSONString(result, PrettyFormat));
            }
        }

        @Override
        public void init() {
            this.config = Config.convert(super.getPluginJobConf());
            this.httpClient=new OkHttp3Client();
        }

        @Override
        public void destroy() {
            this.httpClient.destroy();
        }
    }
}
